package kr.haggenna.sevice.controller;


import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import kr.haggenna.member.dao.MemberDao;
import kr.haggenna.member.domain.MemberCommand;
import kr.haggenna.sevice.dao.ServiceDao;
import kr.haggenna.sevice.domain.ServiceCommand;
import kr.haggenna.sevice.util.PagingUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class ServiceListController {
	
	@Autowired
	private ServiceDao serviceDao;
	@Autowired
	private MemberDao memberDao;
	
	private int pageSize = 10;
	private int blockCount = 10;
	
	@RequestMapping("/serviceList.do")
	public ModelAndView process(@RequestParam(value="pageNum",defaultValue="1")int currentPage,
								HttpSession session){

		ModelAndView mav = new ModelAndView();
		
		String email = (String)session.getAttribute("email");
		MemberCommand memberCommand = null;
		
		int size = 0;
		
		String pagingHtml = "";
		Map<String, Object> map = new HashMap<String,Object>();
		
		int count = serviceDao.getRowCount(map);
		
		PagingUtil page = new PagingUtil(currentPage, count, pageSize, blockCount, "seviceList.do");
		
		pagingHtml = page.getPagingHtml().toString();
		
		map.put("start", page.getStartCount());
		map.put("end", page.getEndCount());
		
		List<ServiceCommand> list = new ArrayList<ServiceCommand>();
		List<ServiceCommand> serviceList = null;
		if(count > 0 ){
			serviceList = serviceDao.list(map);
			
			size = serviceList.size();
			
			for(ServiceCommand service : serviceList){
				if(email.equals("admin")){
					
					memberCommand = new MemberCommand();
					
					list.add(service);
					
					String member_email = service.getEmail();
					
					memberCommand = memberDao.getMember(member_email);
					
					mav.addObject("size", size);

					
				}else if(email.equals(service.getEmail())){
					memberCommand = memberDao.getMember(email);
					list.add(service);
					
					mav.addObject("memberCommand", memberCommand);
					
				}
			}
		}else{
			serviceList = Collections.emptyList();
		}
		
		int number = count-(currentPage-1)*pageSize;
		
		mav.setViewName("serviceList");
		mav.addObject("count", count);
		mav.addObject("size", size);
		mav.addObject("list", list);
		mav.addObject("pagingHtml", pagingHtml);
		mav.addObject("number", number);
		
		return mav;
	}
	
}
